const { Movie, Sentence, Music } = require("../models/classes");
const { Op } = require("sequelize");
const { flatten } = require("lodash");

class Art {

  async getDetail(uid) {
    const {Like} = require('./like');
    const art =  await Art.getData(this.art_id, this.type);
    const like = await Like.userLike(this.art_id, this.type ,uid)
    art.setDataValue('userLike',like)
    return art
  }

  static async getList(artsList) {
    let arts = [];
    const artsIdsList = {
      100: [],
      200: [],
      300: [],
    };

    for (let i = 0; i < artsList.length; i++) {
      const el = artsList[i];
      artsIdsList[el.type].push(el.art_id);
    }

    for (const key in artsIdsList) {
      if (artsIdsList.hasOwnProperty(key)) {
        const ids = artsIdsList[key];
        if (ids.length === 0) {
          continue;
        }
        arts.push(await Art._getListDate(ids, key));
      }
    }
    return flatten(arts);
  }

  static async _getListDate(ids, type) {
    let arts = [];
    const finder = {
      where: {
        id: {
          [Op.in]: ids,
        },
      },
    };

    const scope = "bh";
    if (+type === 100) {
      arts = await Movie.scope(scope).findAll(finder);
    } else if (+type === 200) {
      arts = await Music.scope(scope).findAll(finder);
    } else if (+type === 300) {
      arts = await Sentence.scope(scope).findAll(finder);
    }
    return arts;
  }

  static async getData(id, type, scope = true) {
    let art = null;
    const finder = {
      where: { id },
    };
    scope = scope ? "bh" : null;
    if (+type === 100) {
      art = await Movie.scope(scope).findOne(finder);
    } else if (+type === 200) {
      art = await Music.scope(scope).findOne(finder);
    } else if (+type === 300) {
      art = await Sentence.scope(scope).findOne(finder);
    }else if(+type === 400){
      art = await Sentence.scope(scope).findOne(finder);
    }

    return art;
  }
}
module.exports = {
  Art,
};
